package ldap

import io.vertx.core.Vertx
import io.vertx.ext.auth.ldap.LdapAuthentication
import io.vertx.kotlin.ext.auth.ldap.ldapAuthenticationOptionsOf
import javax.naming.Context
import javax.naming.directory.InitialDirContext
import javax.naming.directory.SearchControls

suspend fun main() {
  val options =
      ldapAuthenticationOptionsOf(
          authenticationQuery = "uid={0},ou=people,dc=medipath,dc=com,dc=cn",
          url = "ldap://172.10.100.192:389",
          authenticationMechanism = "bcrypt",
      )
  val ldapAuthentication = LdapAuthentication.create(Vertx.vertx(), options)
  // val user = ldapAuthentication.authenticate(UsernamePasswordCredentials("jzb",
  // "tomking")).coAwait()
  // println(user)

  search()
}

private fun search() {
  val adminContext =
      InitialDirContext().apply {
        addToEnvironment(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory")
        addToEnvironment(Context.PROVIDER_URL, "ldap://172.10.100.192:389")
        addToEnvironment(Context.SECURITY_AUTHENTICATION, "simple")
        addToEnvironment(Context.SECURITY_PRINCIPAL, "cn=admin,dc=medipath,dc=com,dc=cn")
        addToEnvironment(Context.SECURITY_CREDENTIALS, "medipath888")
      }
  val searchControls =
      SearchControls().apply {
        returningAttributes = arrayOf("dn")
        searchScope = SearchControls.SUBTREE_SCOPE
      }
  val filter = "(&(objectClass=inetOrgPerson)(uid=jzb))"
  val searchResults =
      adminContext.search("ou=people,dc=medipath,dc=com,dc=cn", filter, searchControls)
  for (result in searchResults) {
    println(result.nameInNamespace)
    println(result.attributes)
  }
}
